import {opendir, readFile, writeFile} from 'node:fs/promises';
import path from 'node:path';

/**
 * todo
 * 设置相对路径
 * 设置文档目录
 * 设置图片后缀名
 */
const CurFilePath = './';
const DocDirList = ['./assets'];
const ImageSuffix = ['.png', '.svg', '.jpg'];


/**
 * 获取文档目录
 */
const getDocDirList = async () => {
  const result = [];
  for (const item of DocDirList) {
    const dir = await opendir(item);
    result.push(dir);
  }
  return result;
}

try {
  const list = [];
  const readDir = async (target) => {
    for await (const dirElement of target) {
      if (dirElement.isDirectory()) {
        const childDir = await opendir(`${target.path}/${dirElement.name}`);
        await readDir(childDir);
      } else {
        if (ImageSuffix.some((item) => dirElement.name.endsWith(item))) {
          console.log(`${target.path}/${dirElement.name}`);
          list.push({
            name: dirElement.name,
            src: `${target.path}/${dirElement.name}`,
          });
        }
      }
    }
  };
  const docDirList = await getDocDirList();
  for (const item of docDirList) {
    await readDir(item);
  }
  const tpl = await readFile(path.join(CurFilePath, './template.tpl'), 'utf-8');
  const html = tpl.replace('{{svgList}}', JSON.stringify(list));

  await writeFile('./icon-preview.html', html);
} catch (e) {
  console.warn(e);
}